<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>键盘移动div</title>
    <style>
      #box {
        height: 100px;
        width: 100px;
        background-color: red;
        position: absolute;
      }
    </style>
  </head>
  <body>
    <div id="box"></div>
    <script>
      /* 
        使div可以根据不同的方向键向不同的方向移动
        按左键，div向左移动 -keyCode 37
        按右键，div向右移动 -keyCode 39
        按上键，div向上移动 -keyCode 38
        按下键，div向下移动 -keyCode 40
        每次移动10px
        */
      var box = document.getElementById("box");
      document.onkeyup = function (event) {
        const { keyCode } = event;
        switch (keyCode) {
          case 37:
            move("left", "offsetLeft", -10);
            break;
          case 38:
            move("top", "offsetTop", -10);
            break;
          case 39:
            move("left", "offsetLeft", 10);
            break;
          case 40:
            move("top", "offsetTop", 10);
            break;
          default:
            break;
        }
      };

      function move(orientation, offsetDirection, distance) {
        box.style[orientation] = box[offsetDirection] + distance + "px";
      }
    </script>
  </body>
</html>
